function f1 = latexTable(table, appendToExisting, options)
% ===========================================================================
% Function to create latex table from given matrix and row/column headers.
% This function makes it easier just to embed a table in an existing
% document rather than wrapping a table in a stand alone document.
%
% [Input]:
% table.dataMat: matrix of data
% table.rowLabels:  cell array of row title
% table.colLabels:  cell array of column title(on the top); 
% table.corner:  string, upper left corner of the graph
% table.tableHeader: string of Title name printed on the top of table
%
% appendToExisting    : yes to append to existing file.  Provide file ID in
% options structure in this case.
%
% [Options]: (which are indeed optional)
% options.fileName    : file name to write
% options.outPath     : location of directory for output
% options.orientation : orientation of table, 'portrait' or 'landscape'
% options.fid         : optional file id to append to
% options.leaveOpen   : option to leave file open after writing
%
% [Output]: 
% f1 returns the FID
% Alaways a TeX file contains the LaTeX commands for creating the table
% if options.printPDF, a PDF version of a table
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% This setup makes it easy for user to import this table to his main LaTeX
% article. He/She can do so simply by using the following command: 
% \input(table1.tex)
%
% ===============================================================================
%  RA: Xi Luo
%  Date Created: 05/12/2011
%  RA: Matt Olson
%  Date Modified: 1/3/2012

cucd=cd;

%% 1. Check inputs and set missing ones to default
if ~isfield(table,'corner')
    table.corner ='';
end
if ~isfield(table,'tableHeader')
    table.tableHeader = '';
end
if nargin < 3
    options = [];
end
if ~isfield(options,'outPath')
    options.outPath = cucd;
end

if ~isfield(options,'orientation')
    options.orientation = 'portrait';
end

if ~isfield(table,'rowLabels')
    table.rowLabels = strcat('Row ', num2cprec(1:size(table.dataMat,1)));
end
if ~isfield(table,'colLabels')
    table.colLabels = strcat('Col ', num2cprec(1:size(table.dataMat,2)));
end
if isnumeric(table.dataMat); 
    isnum = 1; 
elseif iscell(table.dataMat); 
    isnum = 0; 
else
    error('datamat has either to be numeric or a cellarray')
end

if ~isfield(options,'leaveOpen')
    options.leaveOpen = false;
end

if appendToExisting
    % Need to specify either fileName OR ID to write to
    if isfield(options,'fileName') && isfield(options, 'fid')
        error('If appending to file, specify EITHER fid or filename, but not both');
    % Check that some place to append to is specified
    elseif ~(isfield(options,'fileName') || isfield(options, 'fid'))
        error('If appending to file, need to specify either fileName OR fid');
    end
else
    if ~isfield(options,'fileName')
        options.fileName='table';
    end
end
    
%% 2. Extract data
datamat = table.dataMat;
rowtit  = table.rowLabels;
coltit  = table.colLabels;
corner  = table.corner;
tablename = table.tableHeader;
outputpath = options.outPath;

[nrow, ncol] = size(datamat);

%% 3. Handle File Writing

if appendToExisting  
    if isfield(options,'fileName')
        f1 = fopen([outputpath '\' options.fileName '.tex'],'a');
    elseif isfield(options,'fid')
        f1 = options.fid;
    end  
else 
    f1 = fopen([options.file '.tex','w']);
end

%% Begin Writing TeX Code to File
stylestr =  '{|l ||';
for ii = 1:ncol
    stylestr = [stylestr, 'c |' ];
end
stylestr =  [stylestr, '}'];

% If table is not empty, write it to file
if ~isempty(datamat)
    fprintf(f1, '\\begin{center} \n');
    fprintf(f1, ['\\begin{longtable}', stylestr, ' \n']);
    fprintf(f1, ['\\hline \n']);
    fprintf(f1, ['\\multicolumn{', num2str(ncol+1), '}{|c|}{', char(tablename),'} \\\\ \n']);
    fprintf(f1, ['\\hline \n']);
    for jj = 1:nrow+1 % row by row
        if jj == 1; % taking care of first row(fill in column title)
            rowstring = char(corner);
            for kk = 1:ncol;
                rowstring = [rowstring, '&', char(coltit{kk})];
            end
        elseif jj > 1;
            rowstring = rowtit{jj-1};
            for kk = 1:ncol % column by column
                if isnum
                    rowstring =  [rowstring, '&', num2str(datamat(jj-1, kk), '%3.2f')];
                else
                    rowstring =  [rowstring, '&', datamat{jj-1, kk}];
                end
            end
        end
        fprintf(f1, [rowstring, '\\\\ \\hline \n']);
    end

    fprintf(f1, '\\end{longtable} \n');
    fprintf(f1, '\\end{center} \n');

end

if ~options.leaveOpen
    fclose(f1);
end

end